package hit.edu.zjc.Tool;
import java.io.File;
import java.util.EnumSet;
import java.util.logging.Level;
import java.util.logging.Logger;

import edu.uci.ics.hyracks.api.client.HyracksConnection;
import edu.uci.ics.hyracks.api.client.IHyracksClientConnection;
import edu.uci.ics.hyracks.api.job.JobFlag;
import edu.uci.ics.hyracks.api.job.JobId;
import edu.uci.ics.hyracks.api.job.JobSpecification;
public class HyracksJobEx 
{
	private static final Logger LOGGER = Logger.getLogger(HyracksJobEx.class.getName());
	public static String cluster_ip="192.168.59.133";//ClusterControler的IP地址
	public static int cluster_port=1098;//ClusterControler的Client端口号
	public static String[] NC_ID_array=null;
	private static IHyracksClientConnection hcc=null;
	public static String AppLibPath;
	public static void initNC()//设置成只需要第一次调用执行。
	{
		//由用户给出。
		//test code
		if(NC_ID_array==null)
		{
			NC_ID_array=new String[2];
			NC_ID_array[0]="NC1";
			NC_ID_array[1]="NC2";
		}
		AppLibPath="/home/chinahitzjc/MyHyracksBin/applib.zip";
	}
	public static boolean connectCluster()
	{
		try 
		{
			initNC();
			hcc = new HyracksConnection(cluster_ip,cluster_port);
			return true;
		} 
		catch (Exception e) 
		{
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return false;
		}
	}
	public static boolean exe_job(JobSpecification spec,String AppName)
	{
		initNC();
		try
		{
			if (LOGGER.isLoggable(Level.INFO)) 
			{
	            LOGGER.info(spec.toJSON().toString(2));
	        }
			if(hcc==null)
				connectCluster();
			try{//防止App被重复创建
			hcc.createApplication(AppName, new File(AppLibPath));
			}
			catch (Exception e)
			{
				hcc.destroyApplication(AppName);
				hcc.createApplication(AppName, new File(AppLibPath));
			}
	       JobId jobId = hcc.startJob(AppName, spec, EnumSet.of(JobFlag.PROFILE_RUNTIME));
	        if (LOGGER.isLoggable(Level.INFO)) {
	            LOGGER.info(jobId.toString());
	        }
	        hcc.waitForCompletion(jobId);
	        
	        return true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}
}
